package com.qinhao.loveCrowdFunding.controller;

import com.qinhao.loveCrowdFunding.enums.ResponseCodeEnum;
import com.qinhao.loveCrowdFunding.handler.MyMessageHandler;
import com.qinhao.loveCrowdFunding.pojo.AdminControlInformationDTO;
import com.qinhao.loveCrowdFunding.pojo.MessageWriteByUserIdEntity;
import com.qinhao.loveCrowdFunding.pojo.TelephoneNumberDTO;
import com.qinhao.loveCrowdFunding.req.*;
import com.qinhao.loveCrowdFunding.resp.*;
import com.qinhao.loveCrowdFunding.service.AdminService;
import com.qinhao.loveCrowdFunding.service.MessageService;
import com.qinhao.loveCrowdFunding.service.SimpleInformationService;
import com.qinhao.loveCrowdFunding.utils.AdminLoginUtil;
import com.qinhao.loveCrowdFunding.utils.AuditControlUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private SimpleInformationService simpleInformationService;
    @Autowired
    private MyMessageHandler myMessageHandler;
    @Autowired
    private MessageService messageService;
    private static final Logger log = Logger.getLogger(AdminController.class);
    // 检测是否有管理员权限
//    @RequestMapping("/login")
//    public AdminLoginResponse hello() {
//        AdminLoginResponse adminLoginResponse = AdminLoginResponse.builder().code(ResponseCodeEnum.SUCCESS.getCode()).build();
//        return adminLoginResponse;
//    }

    // 获取没有审核的众筹信息
    @RequestMapping("/getInformation")
    public AdminControlInformationResponse getInformation(@RequestBody AdminControlInformationRequest adminControlInformationRequest) {
        AdminControlInformationResponse adminControlInformationResponse = AdminControlInformationResponse.builder().build();
        if (!AdminLoginUtil.getHashSet().contains(adminControlInformationRequest.getUserName())) {
            adminControlInformationResponse.setCode(ResponseCodeEnum.PERMISSIONDENIED.getCode());
            return adminControlInformationResponse;
        }
        try {
            AdminControlInformationDTO adminControlInformationDTO = adminService.getInformation();
            if (adminControlInformationDTO != null) {
                BeanUtils.copyProperties(adminControlInformationDTO, adminControlInformationResponse);
            }
            // 设置未审核用户的身份证号码
            for (int i = 0; i < adminControlInformationDTO.getUnapproved().size(); i++) {
                TelephoneNumberDTO telephoneNumber = simpleInformationService.getTelephoneNumber(adminControlInformationResponse.getUnapproved().get(i).getUserId());
                adminControlInformationResponse.getUnapproved().get(i).setTelephoneNumber(telephoneNumber.getTelephoneNumber());
            }
            // 设置被举报用户的身份证号码
            for (int i = 0; i < adminControlInformationDTO.getReported().size(); i++) {
                TelephoneNumberDTO telephoneNumber = simpleInformationService.getTelephoneNumber(adminControlInformationResponse.getReported().get(i).getUserId());
                adminControlInformationResponse.getReported().get(i).setTelephoneNumber(telephoneNumber.getTelephoneNumber());
            }
            // 设置所有众筹信息用户的身份证号码
            for (int i = 0; i < adminControlInformationDTO.getAll().size(); i++) {
                TelephoneNumberDTO telephoneNumber = simpleInformationService.getTelephoneNumber(adminControlInformationResponse.getAll().get(i).getUserId());
                adminControlInformationResponse.getAll().get(i).setTelephoneNumber(telephoneNumber.getTelephoneNumber());
            }
            log.info("get information success.");
            adminControlInformationResponse.setCode(ResponseCodeEnum.SUCCESS.getCode());
        }catch (Exception e) {
            adminControlInformationResponse.setCode(ResponseCodeEnum.FAIL.getCode());
        }
        return adminControlInformationResponse;
    }

    // 审核驳回
    @RequestMapping("/rejectReview")
    public RejectReviewResponse rejectReview(@RequestBody RejectReviewRequest rejectReviewRequest) {
        RejectReviewResponse rejectReviewResponse = RejectReviewResponse.builder().build();
        if (rejectReviewRequest.getId() == null) {
            rejectReviewResponse.setCode(ResponseCodeEnum.SIMPLEINNFORMATIONIDISNULL.getCode());
            return rejectReviewResponse;
        }
        try {
            synchronized (this) {
                if (AuditControlUtil.getVector().contains(rejectReviewRequest.getId() + "")) {
                    rejectReviewResponse.setCode(ResponseCodeEnum.AUDITING.getCode());
                    return rejectReviewResponse;
                }else {
                    AuditControlUtil.getVector().add(rejectReviewRequest.getId() + "");
                }
            }
            adminService.rejectReview(rejectReviewRequest);
            AuditControlUtil.getVector().remove(rejectReviewRequest.getId() + "");
            String message = "你的标题为" + rejectReviewRequest.getTitle() + "的众筹信息未通过审核,原因为" + rejectReviewRequest.getRejectReason() + ",请进行修改";
            sendMessage(message, rejectReviewRequest.getUserId());
            rejectReviewResponse.setCode(ResponseCodeEnum.SUCCESS.getCode());
        }catch (Exception e) {
            rejectReviewResponse.setCode(ResponseCodeEnum.FAIL.getCode());
        }
        return rejectReviewResponse;
    }

    // 审核通过
    @RequestMapping("/approveReview")
    public ApproveReviewResponse approveReview(@RequestBody ApproveReviewRequest approveReviewRequest) {
        ApproveReviewResponse approveReviewResponse = ApproveReviewResponse.builder().build();
        if (approveReviewRequest.getId() == null) {
            approveReviewResponse.setCode(ResponseCodeEnum.SIMPLEINNFORMATIONIDISNULL.getCode());
            return approveReviewResponse;
        }
        try {
            synchronized (this) {
                if (AuditControlUtil.getVector().contains(approveReviewRequest.getId() + "")) {
                    approveReviewResponse.setCode(ResponseCodeEnum.AUDITING.getCode());
                    return approveReviewResponse;
                }else {
                    AuditControlUtil.getVector().add(approveReviewRequest.getId() + "");
                }
            }
            adminService.approveReview(approveReviewRequest);
            AuditControlUtil.getVector().remove(approveReviewRequest.getId() + "");
            // 存储消息
            String message = "你的标题为" + approveReviewRequest.getTitle() + "的众筹信息已经通过审核,项目进行周期为" + approveReviewRequest.getDate() +",请前往查看,等待项目开始日期";
            String notice = "标题为" + approveReviewRequest.getTitle() + "的众筹信息已经发布，大家快去帮助他吧！";
            sendMessage(message, approveReviewRequest.getUserId());
            Set<String> userIds = MyMessageHandler.getUserMap().keySet();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 如果已经到了开始日期
            if (sdf.parse(approveReviewRequest.getFundingCreateTime()).getTime() <= new Date().getTime()) {
                for (String userId : userIds) {
                    sendMessage(notice, Integer.parseInt(userId));
                }
            }
            approveReviewResponse.setCode(ResponseCodeEnum.SUCCESS.getCode());
        } catch (Exception e) {
            approveReviewResponse.setCode(ResponseCodeEnum.FAIL.getCode());
        }
        return approveReviewResponse;
    }

    // 举报驳回
    @RequestMapping("/rejectReport")
    public RejectReportResponse rejectReport(@RequestBody RejectReportRequest rejectReportRequest) {
        RejectReportResponse rejectReportResponse = RejectReportResponse.builder().build();
        if (rejectReportRequest.getSimpleInformationId() == null) {
            rejectReportResponse.setCode(ResponseCodeEnum.SIMPLEINNFORMATIONIDISNULL.getCode());
            return rejectReportResponse;
        }
        try {
            synchronized (this) {
                if (AuditControlUtil.getVector().contains(rejectReportRequest.getSimpleInformationId() + "")) {
                    rejectReportResponse.setCode(ResponseCodeEnum.AUDITING.getCode());
                    return rejectReportResponse;
                }else {
                    AuditControlUtil.getVector().add(rejectReportRequest.getSimpleInformationId() + "");
                }
            }
            adminService.rejectReport(rejectReportRequest);
            AuditControlUtil.getVector().remove(rejectReportRequest.getSimpleInformationId() + "");
            String beReportedFailMessage = "你的众筹标题为" +  rejectReportRequest.getTitle() + "的众筹内容经管理员审核发现没有违规行为,将对该项目重新上线";
            sendMessage(beReportedFailMessage, rejectReportRequest.getUserId());
            rejectReportResponse.setCode(ResponseCodeEnum.SUCCESS.getCode());
        } catch (Exception e) {
            rejectReportResponse.setCode(ResponseCodeEnum.FAIL.getCode());
        }
        return rejectReportResponse;
    }
    // 举报通过
    @RequestMapping("/approveReport")
    public ApproveReportResponse approveReport(@RequestBody ApproveReportRequest approveReportRequest) {
        ApproveReportResponse approveReportResponse = ApproveReportResponse.builder().build();
        if (approveReportRequest.getSimpleInformationId() == null) {
            approveReportResponse.setCode(ResponseCodeEnum.SIMPLEINNFORMATIONIDISNULL.getCode());
            return approveReportResponse;
        }
        try {
            synchronized (this) {
                if (AuditControlUtil.getVector().contains(approveReportRequest.getSimpleInformationId() + "")) {
                    approveReportResponse.setCode(ResponseCodeEnum.AUDITING.getCode());
                    return approveReportResponse;
                }else {
                    AuditControlUtil.getVector().add(approveReportRequest.getSimpleInformationId() + "");
                }
            }
            adminService.approveReport(approveReportRequest);
            AuditControlUtil.getVector().remove(approveReportRequest.getSimpleInformationId() + "");
            String beReportedFailMessage = "你的众筹标题为" +  approveReportRequest.getTitle() + "的众筹内容经管理员审核发现有违规行为,该项目已经异常结束";
            sendMessage(beReportedFailMessage, approveReportRequest.getUserId());
            approveReportResponse.setCode(ResponseCodeEnum.SUCCESS.getCode());
        } catch (Exception e) {
            approveReportResponse.setCode(ResponseCodeEnum.FAIL.getCode());
        }
        return approveReportResponse;
    }
    // 强制下线功能
    @RequestMapping("/forcedOffline")
    public ForcedOfflineResponse forcedOffline(@RequestBody ForcedOfflineRequest forcedOfflineRequest) {
        ForcedOfflineResponse forcedOfflineResponse = ForcedOfflineResponse.builder().build();
        if (forcedOfflineRequest.getId() == null) {
            forcedOfflineResponse.setCode(ResponseCodeEnum.SIMPLEINNFORMATIONIDISNULL.getCode());
            return forcedOfflineResponse;
        }
        try {
            synchronized (this) {
                if (AuditControlUtil.getVector().contains(forcedOfflineRequest.getId() + "")) {
                    forcedOfflineResponse.setCode(ResponseCodeEnum.AUDITING.getCode());
                    return forcedOfflineResponse;
                }else {
                    AuditControlUtil.getVector().add(forcedOfflineRequest.getId() + "");
                }
            }
            adminService.forcedOffline(forcedOfflineRequest);
            AuditControlUtil.getVector().remove(forcedOfflineRequest.getId() + "");
            String beReportedFailMessage = "你的众筹标题为" +  forcedOfflineRequest.getTitle() + "的众筹内容经管理员审核发现有违规行为,已经被强制下线";
            sendMessage(beReportedFailMessage, forcedOfflineRequest.getUserId());
            forcedOfflineResponse.setCode(ResponseCodeEnum.SUCCESS.getCode());
        } catch (Exception e) {
            forcedOfflineResponse.setCode(ResponseCodeEnum.FAIL.getCode());
        }
        return forcedOfflineResponse;
    }
    // 抽取发送消息和存储消息为独立方法
    public void sendMessage(String content, Integer userId) {
        MessageWriteByUserIdEntity messageWriteByUserIdEntity = MessageWriteByUserIdEntity.builder().build();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        messageWriteByUserIdEntity.setDate(date);
        messageWriteByUserIdEntity.setUserId(userId);
        messageWriteByUserIdEntity.setTitle(content);
        messageService.writeUnreadMessageByUserId(messageWriteByUserIdEntity);
        // 发送消息给对应的用户
        myMessageHandler.sendMessageToUser(userId + "", content);
    }
}
